<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of content
 *
 * @author dmitry
 */
require_once 'app/access/db.php';
//=======================================
class Models_Content extends Access_Db {
    //put your code here
    public function getLastAdded($page)
    {
        $page = ($page * 10) - 10 ;
        $result = $this->executeQuery('
            SELECT ID,name,added 
            FROM yyProducts 
            WHERE visible=1 ORDER BY added DESC limit ' . $page . ',10') ;
        while ($row = mysql_fetch_assoc($result))
        {
            $product[$row['ID']] = $row['name'] ;
        }
        
        $result = mysql_fetch_assoc($this->executeQuery('
            SELECT COUNT(ID)
            FROM yyProducts 
            WHERE visible=1')) ;
        $product['count'] = $result['COUNT(ID)'] ;
        return $product ;
    }
    
    public function getCategory($id,$page)
    {
        $page = ($page * 10) - 10 ;
        settype($id, 'integer') ;
        $result = $this->executeQuery('
            SELECT ID, name
            FROM yyProducts
            WHERE visible=1 and categoryID='. $id .' ORDER BY name ASC limit ' . $page . ',10') ;
        
            while ($row = mysql_fetch_assoc($result))
            {
                $product[$row['ID']] = $row['name'] ;
            }
            if (!isset ($product)) {
                    die ('<h3><p>Sorry, not found...</p><a href="/' . $this->path 
                            . '">>>>Back.<<<</a></h3>') ;
                }
            $result = mysql_fetch_assoc($this->executeQuery('
            SELECT COUNT(ID)
            FROM yyProducts 
            WHERE visible=1 and categoryID='. $id)) ;
            $product['count'] = $result['COUNT(ID)'] ;
            return $product ;
         
    }
    
    public function getProduct($id)
    {
        settype($id, 'integer') ;
        $result = $this->executeQuery('
            SELECT yyProducts.ID,yyProducts.name,yyProducts.ratio,
            yyProducts.price,yyProducts.votes,yyPictures.name as picname,yyPictures.path
            FROM yyProducts,yyPictures
            WHERE yyPictures.main=1
            AND yyProducts.ID=yyPictures.productID
            AND yyProducts.visible=1 
            AND yyProducts.ID=' . $id) ;
        return mysql_fetch_assoc($result) ;
    }
    
    public function getPictures($id)
    {
        settype($id, 'integer') ;
        $result = $this->executeQuery('
            SELECT name,path
            FROM yyPictures
            WHERE main=0
            AND productID=' . $id) ;
        while ($row = mysql_fetch_array($result))
        {
            $pictures[$row['name']] = $row['path'] ;
        }
        if (isset ($pictures))
        {
            return $pictures;
        } return false;
        
    }

    public function getProperty($id)
    {
        settype($id, 'integer') ;
        $result = $this->executeQuery('
            SELECT yyProductProperties.value,yyProperties.name
            FROM yyProductProperties,yyProperties
            WHERE yyProductProperties.propertyID=yyProperties.ID 
            AND yyProductProperties.productID=' . $id) ;
        while ($row = mysql_fetch_array($result))
        {
            $property[$row['name']] = $row['value'] ;
        }
        return $property ;
    }

    public function getShortData($id)
    {
        settype($id, 'integer') ;
        $result = $this->executeQuery('
            SELECT yyProducts.ID,yyProducts.ratio,yyProducts.price,yyProducts.uri,
            yyPictures.name,yyPictures.path
            FROM yyProducts,yyPictures
            WHERE yyProducts.ID='.$id.' and yyPictures.productID='. $id .' and yyPictures.main=1') ;
        return mysql_fetch_array($result) ;
    }
    
    public function getDiscuss($id)
    {
        settype($id, 'integer') ;
        $result = $this->executeQuery('
            SELECT ID, userID
            FROM yyProductDiscussion
            WHERE productID=' . $id) ;
        while ($row = mysql_fetch_array($result))
        {
            $discuss[$row['ID']] = $row['userID'] ; 
        }
        if (isset ($discuss)) {
        return $discuss ; } return false ;
    }
    
    public function addComment($commentID,$userID,$productID,$commentContent)
    {
        if (trim($commentContent)) {
            $this->executeQuery("
                INSERT INTO yyProductDiscussion
                (ID,secondID,userID,productID,content,added,visible)
                VALUES (NULL,$commentID,$userID,$productID,'" . mysql_real_escape_string($commentContent) . "',NOW(),1)") ;
        }
    }
    
    public function showCommentForm($id,$userID,$productID)
    {
        echo '<div class="commentform">
                <form action="/' . $this->path . 'products/addcomment/' . $productID . '" method="POST">
                    <input type="hidden" name="id" value="' . $id . '">
                    <input type="hidden" name="user" value="' . $userID . '">
                    <input type="hidden" name="product" value="' . $productID . '">
                    <textarea class="elm1" name="comment" rows="15" cols="80">
                    </textarea>
                    <input type="submit" name="submit" value="commit">
                    <input type="reset" name="reset" value="reset">
                </form>
              </div>' ;
    }
    
    function admButton($id)
    {
        if(!isset ($_SESSION['admHash'])) return '' ;
        if($id !== '')
        {
            return '<a href="/' . $this->path . 'adm/editcomment/' . $id . '">
                       <img src="/' . $this->path . 'public/imgpage/pencil.png">
                    </a>' ;
        } else {
            return '' ;
        }
        
    }


    public function showComments($discuss,$goodsID)
    {
        
        if (!$discuss) {
                echo '<div class="maincomment">' ;
                        if (isset ($_COOKIE['ID']))
                        {
                            $this->showCommentForm(0, $_COOKIE['ID'], $goodsID) ;
                        } else {
                            echo 'Гості не можуть коментувати!' ;
                        }
                echo '</div>' ;
            
            return false ;}
            
        foreach ($discuss as $id => $userID)
        {
            $result = $this->executeQuery('
                SELECT yyProductDiscussion.content,yyProductDiscussion.added,
                yyProductDiscussion.secondID,yyUsers.login
                FROM yyProductDiscussion,yyUsers
                WHERE yyProductDiscussion.visible=1
                AND yyProductDiscussion.ID=' . $id . '
                AND yyUsers.ID=' . $userID) ;
            
            $row = mysql_fetch_assoc($result) ;

                $button = $this->admButton($id) ;

                if ($row['secondID'] == 0)
                {
                    echo '<div class="maincomment">
                            <div class="headcomment">
                                <div class="username"> [' . $row['login'] . ']</div>
                                <div class="date"> added : [' . $row['added'] . ']' . $button . '</div>
                            </div>
                            <div class="commentcontent">' . $row['content'] . '</div>
                            <div class="footcomment">
                                <form action="/' . $this->path . 'products/goods/' . $goodsID . '" method="POST">
                                  <input type="hidden" name="id" value="' . $id . '">
                                  <input type="submit" value="answer">  
                                </form>
                            </div>
                          </div>' ;
                    $exResult = $this->executeQuery('
                    SELECT yyProductDiscussion.content,yyProductDiscussion.added,
                    yyProductDiscussion.secondID,yyUsers.login,yyProductDiscussion.ID as \'subcomment\'
                    FROM yyProductDiscussion,yyUsers
                    WHERE yyProductDiscussion.visible=1
                    AND yyProductDiscussion.secondID=' . $id . '
                    AND yyProductDiscussion.userID=yyUsers.ID
                    ORDER BY yyProductDiscussion.added ASC') ;
                    while ($ex = mysql_fetch_assoc($exResult))
                    {

                            $button = $this->admButton($ex['subcomment']) ;

                        echo '<div class="subcomment">
                            <div class="headcomment">
                                <div class="username">[' . $ex['login'] . ']</div>
                                <div class="date"> added : [' . $ex['added'] . ']' . $button . '</div>
                            </div>
                            <div class="commentcontent">' . $ex['content'] . '</div>
                          </div>' ;
                    }
                    if (isset ($_POST['id']) && $_POST['id'] == $id)
                    {
                        echo '<div class="subcomment">' ;
                        if (isset ($_COOKIE['ID']))
                        {
                            $this->showCommentForm($id, $_COOKIE['ID'], $goodsID) ;
                        } else {
                            echo 'Гості не можуть коментувати!' ;
                        }

                        echo '</div>' ;
                    }
                } 
            
        }
        
        echo '<div class="maincomment">' ;
                    if (isset ($_COOKIE['ID']))
                    {
                        $this->showCommentForm(0, $_COOKIE['ID'], $goodsID) ;
                    } else {
                        echo 'Гості не можуть коментувати!' ;
                    }
        echo '</div>' ;
    }


    public function showProducts($content,$from=NULL)
    {     
        if($from !== NULL)
        {
            $page = ceil($content['count']/10) ;
            unset ($content['count']) ;
        }
        
        if (isset ($content))
        {
            foreach ($content as $id => $name)
            {
                $data = $this->getShortData($id) ;
                echo '<div class="unit">
                           <div>
                           <div class="image">
                                <img src="/' . $this->path . 'public/pic/' .
                                    $data['path'] . $data['name'] .'">
                           </div>
                           <div class="unitname">
                                <a href="/' . $this->path . 'products/goods/' .
                                $data['ID'] . '">' .
                                $name .'</a>
                           </div>
                      </div>
                           <div class="price">' .
                               $data['price']
                           . '</div></div>' ;
            }
            if(isset ($page))
            {

                echo '<div class="navi">' ;

                for($i=1;$i<=$page;$i++)
                {
                    if($i != $from)
                    {
                        echo '<form action="' . $_SERVER['REQUEST_URI'] . '" method="POST">
                        <input type="submit" class="go" name="page" value="' . $i . '">
                          </form>' ;
                    } else {
                        echo '<input type="submit" class="go" name="page" value="' . $i . '" disabled>';
                    }

                }
            }
            echo '</div>' ;
            /*echo '<div class="navi"><form action="" method="POST">
                    <input type="submit" name="back" value="<<<">
                  </form>
                  <form action="" method="POST">
                    <input type="submit" name="forward" value=">>>">
                  </form></div>';*/
         } else {
             echo 'Нічого не знайдено!' ;
         }
        
    }
    
    public function showGoods($id)
    {
        $product = $this->getProduct($id) ;
        $pics = $this->getPictures($id) ;
        $info = $this->getProperty($id) ;
        echo '<div id="goods">
            <div class="tocart">
            <a href="/' . $this->path . 'cart/add/' . $id . '">
                <img src="/' . $this->path . 'public/imgpage/tocart.png"></a>
             </div>
                <div class="goodsname">' . $product['name'] . '</div>
                <div class="goodsprice">' . $product['price'] . ' uah</div>
                <div id="pics">
                    <div id="mainpic">
                        <img src="/' . $this->path . 'public/pic/' .
                        $product['path'] . $product['picname'] . '">
                    </div>
                    <div id="secpic">' ;
        if ($pics)
        {
            foreach ($pics as $name => $path)
            {
                echo '<div class="goodsimage">
                        <a href="/' . $this->path . 'public/pic/' .
                        $path . $name . '" rel="lightbox[' . $id . ']" title="' . $name . '">
                            <img src="/' . $this->path . 'public/pic/' .
                        $path . $name . '"></a>
                      </div>' ;
            }
        }
        echo '</div></div>
              <div id="goodsinfo">' ;
        foreach ($info as $name => $value)
        {
            echo '<div class="line">
                    <div class="propertyname">' . $name . '</div>
                    <div class="propertyvalue">' . $value . '</div>
                  </div>' ;
        }
        echo '</div>
              <div id="discuss">' ;
        $this->showComments($this->getDiscuss($id),$id) ;
        echo '</div></div>' ;
        
        
    }
    
    public function getAll($id,$page)
    {
        $page = ($page * 10) - 10 ;
        $result = $this->executeQuery('
            SELECT yyProducts.ID,yyProducts.name,yyProducts.added 
            FROM yyProducts,yyCategories,yyMenu 
            WHERE yyProducts.visible=1
            AND yyProducts.categoryID = yyCategories.ID
            AND yyCategories.menuID=' . $id .'
            ORDER BY added DESC limit ' . $page . ',10') ;
        while ($row = mysql_fetch_assoc($result))
        {
            $product[$row['ID']] = $row['name'] ;
        }
        if(isset ($product))
        {
            $result = mysql_fetch_assoc($this->executeQuery('
            SELECT COUNT(yyProducts.ID)
            FROM yyProducts,yyCategories
            WHERE yyProducts.visible=1
            AND yyProducts.categoryID = yyCategories.ID
            AND yyCategories.menuID=' . $id)) ;
            $product['count'] = $result['COUNT(yyProducts.ID)'] ;
            return $product ;
        }
 
    }
    
    public function addToCart($id)
    {
        for($i=0;$i<$_SESSION['cart']['count'];$i++)
        {
            if($_SESSION['cart'][$i] == $id)
            {
                header('Location: ' . $_SERVER['HTTP_REFERER']) ;
                return NULL ;
            }
        }
        
        $_SESSION['cart'][$_SESSION['cart']['count']++] = $id ;
        
        header('Location: ' . $_SERVER['HTTP_REFERER']) ;
    }
    
    public function showCart($cart)
    {
        if(isset ($cart))
        {
            
        
        $sum = 0 ;
        echo '<div class="sumcart">
            <form action="/' . $this->path . 'cart" method="POST">' ;
        foreach ($cart as $num => $id)
        {
           if($num !== 'count' and $num !== 'sum')
            {
                
            $result = mysql_fetch_assoc($this->executeQuery('SELECT name,price
                                                             FROM yyProducts
                                                             WHERE ID=' . $id)) ;
            $ex = 0 ;
            if(!isset ($_POST[$id]) or $_POST[$id] == 1 or $_POST[$id] == 0) {$count = 1 ; 
            } else {
                preg_replace("/\D/","",$_POST[$id]) ;
                
                $count = str_replace('-', '', $_POST[$id]) ;
                $count = ceil($count) ;
                $ex = $count * $result['price'] ; }
            $price = $result['price'] + $ex ;
            $sum += $result['price'] + $ex ;
            echo '<div class="line">' ;
            echo '<div class="cartname">' . $num . '-' . $result['name'] .
                    '</div><div class="cartvalue">' . $price  . ' uah
                         <div class="opt"><input type="text" value="' . $count . '" name="' . $id . '">
                             <a href="/' . $this->path . 'cart/del/' . $num . '">
                                 <img src="/' . $this->path . 'public/imgpage/del.png">
                             </a>
                         </div>
                       </div>' ;
            echo '</div>' ;
            }
        }
        echo '<div class="line"><div class="sumname">Summ</div>
            <div class="sumvalue"><b>' . $sum . ' uah</b></div></div>
            <input type="submit" name="ok" value="Підтвердити">' ;
        if(isset ($_POST['ok']))
        {
            echo '<div class="commit">Замовити:<a href="/' . $this->path . 'cart/order">
                <img src="/' . $this->path . 'public/imgpage/ok.png">
                    </a></div>' ;
            $_SESSION['cart']['sum'] = $sum ;
        }
        
        echo '</form>
            </div>' ;
        
        } else {
            echo 'Ваша корзина порожня.';
        }
    }
    
    public function order($cart)
    {
        if($cart['sum'] === 0)
        {
            echo 'Ваша корзина порожня!' ;
            return NULL ;
        }
        $this->executeQuery("INSERT INTO yyUserOrder
                             (ID,userID,sum,status,added)
                             VALUES (NULL,'" . $_COOKIE['ID'] . "','" . $_SESSION['cart']['sum'] . "','0',NOW())") ;
        $last = mysql_fetch_assoc($this->executeQuery('SELECT last_insert_id()
                                                       FROM yyUserOrder')) ;
        unset ($cart['sum']) ;
        unset ($cart['count']) ;
        $query = '' ;
        foreach ($cart as $num => $id)
        {
            $query .= "(NULL,'" . $last['last_insert_id()'] . "','$id')" ;
            if($num !== count($cart)-1)
            {
                $query .= ',' ;
            }
            $this->executeQuery('UPDATE yyProducts
                             SET solded=solded+1
                             WHERE ID=' . $id) ;
        }
        
        
        unset ($_SESSION['cart']) ;
        $_SESSION['cart']['count'] = 0 ;
        
        $this->executeQuery('INSERT INTO yyOrders
                             (ID,userOrderID,productID)
                             VALUES ' . $query) ;
        
        echo 'Ваще замовлення успішно додане до черги!';
    }
    
    public function search($word,$page)
    {
        $page = ($page * 10) - 10 ;
        $word = substr($word, 0, 64) ;
        $word = preg_replace("/[^\w\x7F-\xFF\s]/", " ", $word) ;
        if(strlen($word) < 3)
        {
            echo 'Введіть більше 2-х символів! ';
            return NULL ;
        }
        $result = $this->executeQuery("
            SELECT ID,name
            FROM yyProducts 
            WHERE visible=1 
            AND name LIKE '%$word%'limit $page,10") ;
        while ($row = mysql_fetch_assoc($result))
        {
            $product[$row['ID']] = $row['name'] ;
        }
        if(!isset ($product))
        {
            echo 'Нічого не знайдено!';
        }
        $result = mysql_fetch_assoc($this->executeQuery("
            SELECT COUNT(ID)
            FROM yyProducts 
            WHERE visible=1 
            AND name LIKE '%$word%'limit $page,10")) ;
        $product['count'] = $result['COUNT(ID)'] ;
        return $product ;
    }
    
    public function getTop()
    {
        $result = $this->executeQuery('
            SELECT ID,name
            FROM yyProducts 
            WHERE visible=1 ORDER BY solded DESC limit 3') ;
        while ($row = mysql_fetch_assoc($result))
        {
            $product[$row['ID']] = $row['name'] ;
        }

        return $product ;
    }
    
  
}

?>
